﻿using System;
using System.Linq;
using System.Web.Security;
using Coolite.Ext.Web;
using Pap.Core.Utilities;
using Pap.Data;
using Pap.Web.Modules.Membership.ViewModel;
using Pap.Web.Utils;
using Utils.UIPermission;

namespace Pap.Web.Modules.Membership.Views
{
    /// <summary>
    /// 
    /// </summary>
    public partial class UserLogin : BasePage<UserLoginViewModel>
    {
        #region

        /// <summary>
        /// Gets the mode.
        /// </summary>
        string Mode
        {
            get { return Request.QueryString["Mode"]; }
        }

        #endregion

        /// <summary>
        /// Handles the Clicked event of the wndbtnSubmit control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void wndbtnSubmit_Clicked(object sender, AjaxEventArgs e)
        {
            SubmitData();
        }

        /// <summary>
        /// Submits the data.
        /// </summary>
        [AjaxMethod]
        public void SubmitData()
        {
            IUser currentUser;
            if (ViewModel.LogUserIn(txtName.Text, txtPassword.Text, out currentUser))
            {
                RegistryInfo.UserID = currentUser.UserID;
                UIPermissions.SetPermissions(currentUser.Permissions.Select(perm => perm.PermissionName).ToArray());

                wndLogin.Collapse(true);

                string next = FormsAuthentication.GetRedirectUrl(txtName.Text, true);
                FormsAuthentication.RedirectFromLoginPage(txtName.Text, true);

                if (Mode.IsNullOrEmpty())
                    Response.Redirect(next);
                else Response.Redirect("~/Default.aspx");
            }
            else
            {
                txtPassword.MarkInvalid(GetLocalResourceObject("InvalidPassword").ToString());
                wndbtnSubmit.Disabled = false;
            }
        }
    }
}
